package kd.bos.kdec.pincar;

import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.filter.FilterParameter;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.Label;
import kd.bos.form.events.BeforeClosedEvent;
import kd.bos.form.events.CustomEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.BillList;
import kd.bos.list.events.ListRowClickEvent;
import kd.bos.list.events.ListRowClickListener;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 拼车搜索地址（高德）
 * 
 * @author zhangyizhe
 *
 */
public class PinCarForMobSearch extends AbstractFormPlugin implements ListRowClickListener {

	private String[] buttons = new String[] { "home", "company" };

	@Override
	public void registerListener(EventObject e) {
		super.registerListener(e);
		this.addClickListeners(this.buttons);
		BillList billList = this.getControl("billlistap");
		billList.addListRowClickListener(this);
	}

	@Override
	public void click(EventObject evt) {
		super.click(evt);
		Control control = (Control) evt.getSource();
		String key = control.getKey();
		IDataModel model = this.getModel();
		IFormView view = this.getView();
		if (StringUtils.equals("home", key)) {// 设为家/回家
			if (!StringUtils.equals("", model.getValue("home2").toString())) {// 回家
				model.setValue("local", model.getValue("homelocal2"));
				model.setValue("placename", model.getValue("home2"));
				this.getView().close();
			} else {
				if (StringUtils.equals("", model.getValue("placename").toString())) {
					view.showMessage("请搜索一个地址设置为家");
					return;
				}
				// 更新乘客记录字段-家
				long userId = Long.parseLong(RequestContext.get().getUserId());
				long orgId = RequestContext.get().getOrgId();
				QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
				reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
				DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
						"home,homelocal,company,companylocal", reportfilter.toArray());
				if (null == report) {// 无乘客数据
					report = BusinessDataServiceHelper.newDynamicObject("kdec_pincar_reportbill");// 表单标识
					// 设置单据属性
					report.set("billno", System.currentTimeMillis());
					report.set("billstatus", "B");
					report.set("creator", userId);
					report.set("orgfield", RequestContext.get().getOrgId());
					report.set("home", model.getValue("placename").toString());
					report.set("homelocal", model.getValue("local"));
				} else if (report != null) {// 有数据
					// 更新
					report.set("home", model.getValue("placename").toString());
					report.set("homelocal", model.getValue("local"));
				}
				SaveServiceHelper.save(new DynamicObject[] { report });
				Label label = this.getControl("homeplace");
				label.setText(model.getValue("placename").toString());
				Label home1 = this.getControl("home1");
				home1.setText("家");
				view.setVisible(true, "homeplace");
			}
		} else if (StringUtils.equals("company", key)) {// 设为公司/去公司
			if (!StringUtils.equals("", model.getValue("company2").toString())) {// 去公司
				model.setValue("local", model.getValue("companylocal2"));
				model.setValue("placename", model.getValue("company2"));
				this.getView().close();
			} else {
				if (StringUtils.equals("", model.getValue("placename").toString())) {
					view.showMessage("请搜索一个地址设置为公司");
					return;
				}
				// 更新乘客记录字段-公司
				long userId = Long.parseLong(RequestContext.get().getUserId());
				long orgId = RequestContext.get().getOrgId();
				QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
				reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
				DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
						"home,homelocal,company,companylocal", reportfilter.toArray());
				if (null == report) {// 无乘客数据
					report = BusinessDataServiceHelper.newDynamicObject("kdec_pincar_reportbill");// 表单标识
					// 设置单据属性
					report.set("billno", System.currentTimeMillis());
					report.set("billstatus", "B");
					report.set("creator", userId);
					report.set("orgfield", RequestContext.get().getOrgId());
					report.set("company", model.getValue("placename").toString());
					report.set("companylocal", model.getValue("local"));
				} else if (report != null) {// 有数据
					// 更新
					report.set("company", model.getValue("placename").toString());
					report.set("companylocal", model.getValue("local"));
				}
				SaveServiceHelper.save(new DynamicObject[] { report });
				Label label = this.getControl("companyplace");
				label.setText(model.getValue("placename").toString());
				Label home1 = this.getControl("company1");
				home1.setText("公司");
				view.setVisible(true, "companyplace");
			}
		}
	}

	@Override
	public void customEvent(CustomEventArgs e) {
		super.customEvent(e);
		String eventName = e.getEventName();
		String placeResult = e.getEventArgs();
		IDataModel model = this.getModel();
		if (StringUtils.equals("updateData", eventName)) {
			String place = "";
			String districtAddress = "";
			JSONObject point = new JSONObject();
			JSONObject jsonObject = JSONObject.fromObject(placeResult);
			place=jsonObject.containsKey("value")?jsonObject.getString("value"):"";
			point=jsonObject.containsKey("point")?jsonObject.getJSONObject("point"):point;
			JSONObject result=jsonObject.getJSONObject("result");
			districtAddress=result.getString("province")+result.getString("city")+place;
//			for (int i = 0; i < jsonArray.size(); i++) {
//				JSONArray array1 = (JSONArray) jsonArray.get(i);
//				if (StringUtils.equals("value", array1.get(0).toString())) {
//					place = array1.get(1).toString();
//				} else if (StringUtils.equals("tips", array1.get(0).toString())) {
//					JSONArray tipsList = (JSONArray) array1.get(1);
//					for (int j = 0; j < tipsList.size(); j++) {
//						JSONObject obj = tipsList.getJSONObject(j);
//						if (StringUtils.equals(place, obj.get("name").toString())) {
//							location = obj.getJSONObject("location");
//							districtAddress = obj.getString("district") + obj.getString("address");
//						}
//					}
//				}
//			}
			//坐标
			model.setValue("local", point);
			model.setValue("placename", place);
			model.setValue("districtAddress", districtAddress);
		}
	}

	@Override
	public void beforeClosed(BeforeClosedEvent e) {
		super.beforeClosed(e);
		IDataModel model = this.getModel();
		if (!StringUtils.equals("", model.getValue("placename").toString())) {
			long userId = Long.parseLong(RequestContext.get().getUserId());
			long orgId = RequestContext.get().getOrgId();
			// 判断是否有历史记录
			QFilter hisFilter = new QFilter("pass", QCP.equals, userId);
			hisFilter.and(new QFilter("org", QCP.equals, orgId));
			hisFilter.and(new QFilter("placename", QCP.equals, model.getValue("placename")));
			DynamicObject his = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_placehis",
					"placename,createdate", hisFilter.toArray());
			if (null != his) {// 有 -更新
				his.set("createdate", new Date());
				SaveServiceHelper.save(new DynamicObject[] { his });
			} else {// 无数据 -新增
				// 添加写历史是搜索记录
				DynamicObject bill = BusinessDataServiceHelper.newDynamicObject("kdec_pincar_placehis");// 表单标识
				// 设置单据属性
				bill.set("placename", model.getValue("placename"));
				bill.set("placelocal", model.getValue("local"));
				bill.set("pass", RequestContext.get().getUserId());
				bill.set("org", RequestContext.get().getOrgId());
				bill.set("districtaddress", model.getValue("districtAddress"));
				bill.set("createdate", new Date());
				SaveServiceHelper.save(new DynamicObject[] { bill });
			}
		}
		// close返回父页面数据
		Map<String, Object> returnDate = new HashMap<String, Object>();
		returnDate.put("place", model.getValue("placename"));// 地理位置名字
		returnDate.put("local", model.getValue("local"));// 地理位置坐标
		this.getView().returnDataToParent(returnDate);
	}

	@Override
	public void beforeBindData(EventObject e) {
		super.beforeBindData(e);
		IDataModel model = this.getModel();
		IFormView view = this.getView();
		FormShowParameter parameter = this.getView().getFormShowParameter();
		if (StringUtils.equals("kdec_pincar_nomalplace", parameter.getParentFormId())) {
			// 如果是设置常用地址进入就隐藏常用地址面板
			view.setVisible(false, "flex_notreimburse");
		}
		long userId = Long.parseLong(RequestContext.get().getUserId());
		long orgId = RequestContext.get().getOrgId();
		QFilter reportfilter = new QFilter("creator", QCP.equals, userId);
		reportfilter.and(new QFilter("orgfield", QCP.equals, orgId));
		DynamicObject report = BusinessDataServiceHelper.loadSingleFromCache("kdec_pincar_reportbill",
				"home,homelocal,company,companylocal", reportfilter.toArray());
		if (null != report) {
			if (!StringUtils.equals("", report.getString("home"))) {
				Label label = this.getControl("homeplace");
				label.setText(report.getString("home"));
				model.setValue("home2", report.getString("home"));
				model.setValue("homelocal2", report.getString("homelocal"));
				Label home1 = this.getControl("home1");
				home1.setText("家");
				view.setVisible(true, "homeplace");
			}
			if (!StringUtils.equals("", report.getString("company"))) {
				Label label = this.getControl("companyplace");
				label.setText(report.getString("company"));
				model.setValue("company2", report.getString("company"));
				model.setValue("companylocal2", report.getString("companylocal"));
				Label home1 = this.getControl("company1");
				home1.setText("公司");
				view.setVisible(true, "companyplace");
			}
		}
		// 加载单据列表添加筛选条件
		BillList billList = this.getControl("billlistap");
		FilterParameter filterParameter = new FilterParameter();
		// 登录用户隔离
		QFilter filter = new QFilter("pass", QCP.equals, userId);
		QFilter filter1 = new QFilter("org", QCP.equals, orgId);
		List<QFilter> qFilters = new ArrayList<>();
		qFilters.add(filter);
		qFilters.add(filter1);
		filterParameter.setQFilters(qFilters);
		billList.setFilterParameter(filterParameter);
	}

	@Override
	public void afterBindData(EventObject e) {
		super.afterBindData(e);

	}

	@Override
	public void listRowClick(ListRowClickEvent evt) {
		IDataModel model = this.getModel();
		ListRowClickListener.super.listRowClick(evt);
		// 选中历史直接回传数据
		BillList billList = this.getControl("billlistap");
		ListSelectedRow listSelectedRow = billList.getCurrentSelectedRowInfo();
		Long pk = (Long) listSelectedRow.getPrimaryKeyValue();
		DynamicObject his = BusinessDataServiceHelper.loadSingleFromCache(pk, "kdec_pincar_placehis",
				"placename,placelocal");
		model.setValue("local", his.get("placelocal"));
		model.setValue("placename", his.get("placename"));
		this.getView().close();
	}
}
